import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DickYang
 * Date: 2023-07-12
 * Time: 14:59
 */
public class MyBinaryTree {

    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

//    private TreeNode root;

    //手动创建一个树
    TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.left = H;

        return A;
    }

    // 获取树中节点的个数
    private int count = 0;//如果一个对象调用了两次，则结果就出错！
    int size(TreeNode root) {
        if (root == null) {
            return 0;
        }
//        count++;
//        size(root.left);
//        size(root.right);
//        return count;
        return size(root.left) + size(root.right) + 1;
    }
    // 获取叶子节点的个数
    int getLeafTreeNodeCount(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        int leftSize = getLeafTreeNodeCount(root.left);
        int rightSize = getLeafTreeNodeCount(root.right);

        return leftSize+rightSize;
    }
    // 子问题思路-求叶子结点个数

// 获取第K层节点的个数
    int getKLevelTreeNodeCount(TreeNode root,int k) {
        if (root == null) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        int leftSize = getKLevelTreeNodeCount(root.left,k-1);
        int rightSize = getKLevelTreeNodeCount(root.right,k-1);
        return leftSize+rightSize;
    }
    // 获取二叉树的高度
    int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftSize = getHeight(root.left);
        int rightSize = getHeight(root.right);

        return (leftSize > rightSize) ? leftSize+1 : rightSize+1;
    }
    // 检测值为value的元素是否存在
    TreeNode find(TreeNode root, int val) {
        if (root == null) {
            return null;
        }
        if (root.val == val) {
            return root;
        }
        TreeNode leftTreeNode = find(root.left,val);
        if (leftTreeNode != null) {
            return leftTreeNode;
        }
        TreeNode rightTreeNode = find(root.right,val);
        if (rightTreeNode != null) {
            return rightTreeNode;
        }
        return null;
    }
    //层序遍历
    void levelOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val + " ");
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }


    public List<List<Character>> levelOrder1(TreeNode root) {
        List<List<Character>> list = new ArrayList<>();

        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            int size = queue.size();
            List<Character> tmp = new ArrayList<>();
            while(size != 0) {
                TreeNode cur = queue.poll();
                tmp.add(cur.val);
                size--;
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            list.add(tmp);
        }
        return list;
    }
    // 判断一棵树是不是完全二叉树
    boolean isCompleteTree(TreeNode root) {
        if (root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();

        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                break;
            }
        }
        while(!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            if (tmp != null) {
                return false;
            }
        }
        return true;
    }


    // 前序遍历
    void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }
    //二叉树前序非递归遍历
    public List<Character> unLoopPreorderTraversal(TreeNode root) {
        List<Character> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        TreeNode cur = root;
        Deque<TreeNode> stack = new ArrayDeque<>();
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                list.add(cur.val);
                cur = cur.left;
            }
            TreeNode tmp = stack.poll();
            cur = tmp.right;
        }
        return list;
    }
    // 中序遍历
    void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }
    //二叉树中序非递归遍历
    public List<Character> unLoopInorderTraversal(TreeNode root) {
        List<Character> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        TreeNode cur = root;
        Deque<TreeNode> stack = new ArrayDeque<>();
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode tmp = stack.poll();
            list.add(tmp.val);
            cur = tmp.right;
        }
        return list;
    }
    // 后序遍历
    void postOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");

    }
    //二叉树后序非递归遍历
    public List<Character> unLoopPostorderTraversal(TreeNode root) {
        List<Character> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        TreeNode cur = root;
        TreeNode prev = null;
        Deque<TreeNode> stack = new ArrayDeque<>();
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode tmp = stack.peek();
            if (tmp.right == null || tmp.right == prev) {
                list.add(tmp.val);
                stack.pop();
                prev = tmp;
            }else {
                cur = tmp.right;
            }
        }
        return list;
    }

    public List<Character> preorderTraversal(TreeNode root) {
        List<Character> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        list.add(root.val);
        List<Character> leftTree = preorderTraversal(root.left);
        list.addAll(leftTree);

        List<Character> rightTree = preorderTraversal(root.right);
        list.addAll(rightTree);
        return list;
    }

    //判断两棵树是否相同
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q != null || p != null && q ==null) {
            return false;
        }
        //走到这说明都为空或者都不为空
        if (p == null && q == null) {
            return true;
        }
        if (p.val != q.val) {
            // (p.val == q.val)是不可以的,否则下面的递归执行不到了
            return false;
        }
        return isSameTree(p.left,q.left)
                && isSameTree(p.right,q.right);
    }

    //判断是不是另一个数的子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null || subRoot == null) {
            return false;
        }
        if(isSameTree(root,subRoot)) {
         return true;
        }
        if(isSubtree(root.left,subRoot)) {
            return true;
        }
        if (isSubtree(root.right,subRoot)) {
            return true;
        }
        return false;
    }

    //翻转二叉树
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }

        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

    //平衡二叉树 时间复杂度O(n^n)
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }

        int leftSize = getHeight(root.left);
        int rightSize = getHeight(root.right);

        //如果左树与右树之差小于2 并且它们的子树也是.则说明这棵树是平衡二叉树
        if(Math.abs(leftSize - rightSize) < 2
                && isBalanced(root.left)
                && isBalanced(root.right)) {
            return true;
        }
        return false;
    }

    //平衡二叉树的第二种方法 时间复杂度O(n)
    public boolean isBalanced1(TreeNode root) {
        return getHeight1(root) > -1;
    }

    int getHeight1(TreeNode root) {
        if (root == null) {
            return 0;
        }

        //在子树中如果不满足平衡就直接返回-1
        int leftSize = getHeight(root.left);
        if(leftSize < 0) {
            return -1;
        }
        int rightSize = getHeight(root.right);
        if(rightSize < 0) {
            return -1;
        }

        if (Math.abs(leftSize - rightSize) <=1
        /** && leftSize >= 0 && rightSize >= 0 */) {
            return Math.max(leftSize,rightSize)+1;
        } else {
            return -1;
        }
    }


    //判断是否是对称树
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return false;
        }
        return func(root.left,root.right);
    }

    private boolean func(TreeNode leftNode,TreeNode rightNode) {
        if (leftNode == null && rightNode != null
                || leftNode != null && rightNode == null) {
            return false;
        }
        if (leftNode == null && rightNode == null) {
            return true;
        }
        if (leftNode.val != rightNode.val) {
            return false;
        }
        return func(leftNode.left,rightNode.right)
                && func(leftNode.right,rightNode.left);
    }

    /**读入用户输入的一串先序遍历字符串，根据此字符串建立一个二叉树（以指针方式存储）。
    例如如下的先序遍历字符串： ABC##DE#G##F### 其中“#”表示的是空格，
    空格字符代表空树。建立起此二叉树以后，再对二叉树进行中序遍历，输出遍历结果*/
    public static int i = 0;
    public static TreeNode createTree(String str) {
        TreeNode root = null;
        if (str.charAt(i) != '#') {
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = createTree(str);
            root.right = createTree(str);
        } else {
            i++;
        }
        return root;
    }

    //最近公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (root == p || root == q) {
            return root;
        }
        TreeNode leftNode = lowestCommonAncestor(root.left,p,q);
        TreeNode rightNode = lowestCommonAncestor(root.right,p,q);

        if (leftNode != null && rightNode != null) {
            return root;
        } else if (leftNode != null) {
            return leftNode;
        } else if (rightNode != null) {
            return rightNode;
        }
        return null;
    }

    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        Deque<TreeNode> stack1 = new LinkedList<>();
        getPath(root,p,stack1);

        Deque<TreeNode> stack2 = new LinkedList<>();
        getPath(root,q,stack2);

        int size = 0;
        if (stack1.size() - stack2.size() > 0) {
            size = stack1.size() - stack2.size();
            while (size != 0) {
                stack1.poll();
                size--;
            }
        } else {
            size = stack2.size() - stack1.size();
            while (size != 0) {
                stack2.poll();
                size--;
            }
        }
        while(!stack1.isEmpty()) {
            TreeNode ret1 = stack1.poll();
            TreeNode ret2 = stack2.poll();
            if (ret1.val == ret2.val) {
                return ret1;
            }
        }
        return null;
    }
    private boolean getPath(TreeNode root, TreeNode node, Deque<TreeNode> stack) {
        if (root == null || node == null) {
            return false;
        }
        stack.push(root);
        if (root == node) {
            return true;
        }
        boolean leftRet = getPath(root.left,node,stack);
        if (leftRet) {
            return true;
        }
        boolean rightRet = getPath(root.right,node,stack);
        if (rightRet) {
            return true;
        }
        stack.poll();
        return false;
    }


    //根据前序和中序构造出一个二叉树
    public int n;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }

    public TreeNode buildTreeChild(int[] preorder, int[] inorder,int inbegin,int inend) {
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode((char) preorder[n]);
        int rootIndex = findInorderIndex(inorder,inbegin,inend,preorder[i]);
        i++;
        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);
        return root;
    }

    private int findInorderIndex(int[] inorder,int inbegin,int inend,int key) {
        while(inbegin <= inend) {
            if(inorder[inbegin] == key) {
                return inbegin;
            }
            inbegin++;
        }
        return -1;
    }

    //根据二叉树创建字符串
    public String tree2str(TreeNode root) {
        if (root == null) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        tree2strLoop(root,stringBuilder);
        return stringBuilder.toString();
    }
    private void tree2strLoop(TreeNode root, StringBuilder stringBuilder) {
        stringBuilder.append(root.val);
        if (root.left != null) { // 左边不为空时
            stringBuilder.append('(');
            tree2strLoop(root.left,stringBuilder);
            stringBuilder.append(')');
        } else { //左边为空
            if (root.right != null) { // 右边不为空
                stringBuilder.append("()");
            }else { // 右边为空
                return;
            }
        }

        if (root.right != null) { // 右边不为空
            stringBuilder.append('(');
            tree2strLoop(root.right,stringBuilder);
            stringBuilder.append(')');
        } else { // 右边为空
            return;
        }
    }
}
